package root

import (
	"goProject/db"
	"net/http"

	"gitee.com/ruige_fun/util/std"

	"github.com/kataras/iris/v12"
)

type rAllStatus struct {
	Name      string `json:"name"`
	Heartbeat int64  `json:"heartbeat"`
	Port      int64  `json:"port"`
	Goroutine int64  `json:"goroutine"`
	BuildTime string `json:"build_time"`
}

func allStatus(c iris.Context) {
	var result = make([]rAllStatus, 0, 100)
	all, err := db.ServerHeartbeat.GetAll()
	if err != nil {
		c.JSON(std.NewResp(http.StatusOK, "", result, nil))
		return
	}
	for k, d := range all {
		var item = rAllStatus{
			Name:      k,
			Heartbeat: d,
			Port:      0,
			Goroutine: 0,
			BuildTime: "",
		}
		item.Port, _ = db.ServerPort.Get(k)
		item.Goroutine, _ = db.ServerGoroutine.Get(k)
		item.BuildTime, _ = db.ServerBuildTime.Get(k)
		result = append(result, item)
	}
	result = sortAllStatus(result)
	c.JSON(std.NewResp(http.StatusOK, "", result, nil))
}

func sortAllStatus(list []rAllStatus) []rAllStatus {
	for i := 0; i < len(list)-1; i++ {
		for j := i + 1; j < len(list); j++ {
			if list[i].Port > list[j].Port {
				list[i], list[j] = list[j], list[i]
			}
		}
	}
	return list
}
